# -*- coding: utf-8 -*-
from common import logable, trace_method, NDW_DEBUG

__author__ = 'sysprog'

@logable
class ControlCompiledCheckSum(object):
    def __init__(self):
        self.checksum = ""

    @trace_method
    def compile(self, args_list):
        import subprocess
        import hashlib
        import os
        import tempfile

        invoke_list = []

        # remove -o option from the command line
        ii = iter(args_list)
        for it in ii:
            if it == "-o":
                ii.next()
            else:
                invoke_list.append(it)

        temp_result_name = tempfile.mktemp()

        invoke_list.extend(["-o", temp_result_name])

        self.log(NDW_DEBUG, "compile command is '%s'", invoke_list)

        subprocess.call(invoke_list)

        sha256ciper = hashlib.sha256()

        with open(temp_result_name, "r") as f:
            sha256ciper.update(f.read())

        self.checksum = sha256ciper.hexdigest()

        if os.path.exists(temp_result_name):
            os.remove(temp_result_name)